<?php


namespace App\Engine;


use App\Exceptions\ApiException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class BaseModel extends Model
{
    public $timestamps = false;
    protected $dateFormat = 'U';
    /**
     * @param $key
     * @param $value
     * @param $getValue
     * @return mixed
     */
    public static function getValueInKey($key,$value,$getValue)
    {
        return self::where($key,$value)->value($getValue);
    }

    public function getCreatedAtAttribute($value)
    {
        return date("Y-m-d H:i:s",$value);
    }

    public function getUpdatedAtAttribute($value)
    {
        return date("Y-m-d H:i:s",$value);
    }

    public function setStartTimeAttribute($value)
    {
        $this->attributes['start_time']=strtotime($value);
    }

    public function getStartTimeAttribute($value)
    {

        if($value)
            return date("Y-m-d H:i:s",$value);
        return $value;
    }

    public function setEndTimeAttribute($value)
    {

        $this->attributes['end_time']=strtotime($value);

    }

    public function getEndTimeAttribute($value)
    {
        if($value)
            return date("Y-m-d H:i:s",$value);
        return $value;
    }

    public static function CacheById($id,$class,$select=['*'])
    {
        $cache_name=$id.'--'.$class;
        $res=Cache::get($cache_name);
        if(!$res){
            $res=self::where('id',$id)->select($select)->first();
            if (!$res)
                throw new ApiException("数据不存在");
            Cache::put($cache_name,$res,config('setting.token_expire_in'));
        }
        return $res;
    }

    public static function CacheByWhere($class,$where=[],$select=['*'])
    {
        $res=Cache::get($class);
        if(!$res){
            $res=self::where($where)->select($select)->get();
            Cache::put($class,$res,config('setting.token_expire_in'));
        }
        return $res;
    }

    public static function CacheByWhereOder($class,$where=[],$select=['*'],$order='id',$by="desc")
    {
        $res=Cache::get($class);
        if(!$res){
            $res=self::where($where)->orderBy($order,$by)->select($select)->get();
            Cache::put($class,$res,config('setting.token_expire_in'));
        }
        return $res;
    }

    public static function CacheWithOrder($class,$with,$order='id',$by="desc")
    {

    }





}
